<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="学校名称" prop="schoolId" v-if="infoType">
        <el-select
          @change="schoolChange"
          v-model.trim="formData.schoolId"
          clearable
          filterable
          placeholder="请选择学校"
        >
          <el-option
            v-for="item in schoolList"
            :key="item.id"
            :label="item.schoolName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="机构名称" prop="collegeId" v-if="infoType">
        <el-select
          @change="collegeChange"
          v-model.trim="formData.collegeId"
          clearable
          filterable
          placeholder="请选择机构"
          :disabled="!formData.schoolId"
        >
          <el-option
            v-for="item in collegeList"
            :key="item.id"
            :label="item.collegeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="专业名称" prop="majorId">
        <el-select
          @change="majorChange"
          v-model.trim="formData.majorId"
          clearable
          filterable
          placeholder="请选择专业"
          :disabled="!formData.schoolId"
        >
          <el-option
            v-for="item in majorList"
            :key="item.id"
            :label="item.majorName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班级名称" prop="classesId" v-if="infoType">
        <el-select
          @change="classesChange"
          v-model.trim="formData.classesId"
          clearable
          filterable
          placeholder="请选择班级"
          :disabled="!formData.schoolId"
        >
          <el-option
            v-for="item in classesList"
            :key="item.id"
            :label="item.classesName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学生姓名" prop="studentId" v-if="infoType">
        <el-select
          v-model.trim="formData.studentId"
          clearable
          filterable
          placeholder="请选择学生"
          :disabled="!formData.classesId"
        >
          <el-option
            v-for="item in studentList"
            :key="item.id"
            :label="item.studentName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <GenerateResultTableDialog ref="generateResultTableDialog" />
</template>
<script lang="ts" name="SystemUserForm" setup>
import * as UserApi from '@/api/member/index'
import * as CollegeApi from '@/api/cmis/college'
import * as ClassesApi from '@/api/cmis/classes'
import * as SchoolApi from '@/api/cmis/school'
import * as StudentApi from '@/api/cmis/student'
import * as MajorApi from '@/api/cmis/major'

const { t } = useI18n() // 国际化
const dialogVisible = ref(false) // 弹窗的是否展示
const infoType = ref(true) // 编辑时隐藏下拉状态
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  schoolId: undefined,
  collegeId: undefined,
  majorId: undefined,
  classesId: undefined,
  studentId: undefined
})
const formRules = reactive({
  schoolId: [{ required: true, message: '学校不能为空', trigger: 'blur' }]
  // collegeId: [{ required: true, message: '机构不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const schoolList = ref([]) //学校列表
const collegeList = ref([]) //机构列表
const majorList = ref([]) //专业列表
const classesList = ref([]) //机构列表
const studentList = ref([]) //机构列表

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  dialogTitle.value = t('集体新增')
  resetForm()
  // 加载学校列表
  schoolList.value = await SchoolApi.getSchoolList(null)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const schoolChange = async (value: any) => {
  formData.value.collegeId = undefined
  formData.value.majorId = undefined
  formData.value.classesId = undefined
  formData.value.studentId = undefined

  if (value) {
    // 加载学校列表并开启选择
    collegeList.value = await CollegeApi.getCollegeList(formData.value)
    // 获取专业列表
    getMajorList()
    // 加载机构列表并开启选择
    getClassesList()
  }
}

const collegeChange = async () => {
  formData.value.majorId = undefined
  formData.value.classesId = undefined
  formData.value.studentId = undefined

  // 获取专业列表
  getMajorList()
  // 加载机构列表并开启选择
  getClassesList()
}

const majorChange = async () => {
  formData.value.classesId = undefined
  formData.value.studentId = undefined

  // 加载机构列表并开启选择
  getClassesList()
}

const classesChange = async () => {
  formData.value.studentId = undefined

  // 加载学生列表并开启选择
  studentList.value = await StudentApi.getStudentList(formData.value)
}

// 获取专业列表
const getMajorList = async () => {
  const res = await MajorApi.getMajorList({
    schoolId: formData.value.schoolId,
    collegeId: formData.value.collegeId
  })
  majorList.value = res
}

// 获取班级列表
const getClassesList = async () => {
  classesList.value = await ClassesApi.getClassesList(formData.value)
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as UserApi.StudentUserVO
    const res = await UserApi.createStudentUser(data)
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    openGenerateResultTableDialog(res)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    schoolId: undefined,
    collegeId: undefined,
    majorId: undefined,
    classesId: undefined,
    studentId: undefined
  }
  formRef.value?.resetFields()
}

/**
 * 生成后回显的内容
 */
const labelMap = ref({
  studentName: '学生姓名',
  studentCode: '学生编号',
  msg: '信息'
})
const generateResultTableDialog = ref()
const openGenerateResultTableDialog = (res) => {
  generateResultTableDialog.value.open(labelMap.value, res)
}
</script>
